﻿using Api.Models;
using Api.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace Api.Controllers
{
    [ApiController]
    [Route("Api/[controller]")]
    public class AuthController : ControllerBase
    {
        private readonly IAuthService _authService;

        private readonly ISqlSugarClient _client;

        public AuthController(IAuthService authService, ISqlSugarClient client)
        {
            _authService = authService;
            _client = client;
        }

        [HttpPost("Register")]
        public async Task<ActionResult<AuthResponse>> Register([FromBody] RegisterRequest request)
        {
            try
            {
                var user = await _authService.Register(request.Username, request.Email, request.Password);
                var response = await _authService.Login(request.Email, request.Password);
                return Ok(response);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        [HttpPost("Login")]
        public async Task<ActionResult<AuthResponse>> Login([FromBody] LoginRequest request)
        {
            try
            {

                var response = await _authService.Login(request.Email, request.Password);
                return Ok(response);
            }
            catch (Exception ex)
            {
                return Unauthorized(ex.Message);
            }
        }

        [HttpGet("All")]
         public IActionResult All()
        {
            try
            {
                var users = _client.Queryable<User>().ToList();
                if (users == null) return Ok(new { });
                return Ok(users);
            }
            catch (Exception ex)
            {
                return Unauthorized(ex.Message);
            }
        }
    }
}
